package com.cn.steam.iam.config;

import com.cn.steam.foundation.common.web.config.jwt.CommonAccessDeniedHandler;
import com.cn.steam.foundation.common.web.config.jwt.CommonAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import static com.cn.steam.foundation.common.model.CommonConstant.COMMON_PUBLIC_APIS_PATTERN;
import static com.cn.steam.foundation.common.model.CommonConstant.COMMON_STATIC_RESOURCE_PATTERN;
import static com.cn.steam.foundation.common.model.CommonConstant.SWAGGER_RESOURCES;
/**
 * 资源服务器配置
 * @author: zjm
 * @create: 2021-11-20 13:30
 **/
@Configuration
//开启资源服务器，简化访问规则
@EnableResourceServer
public class IamResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Autowired
    private CommonAuthenticationEntryPoint commonAuthenticationEntryPoint;

    @Autowired
    private CommonAccessDeniedHandler commonAccessDeniedHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(commonAuthenticationEntryPoint)
                .accessDeniedHandler(commonAccessDeniedHandler)
                .and()
                .authorizeRequests()
                .antMatchers(COMMON_PUBLIC_APIS_PATTERN, COMMON_STATIC_RESOURCE_PATTERN).permitAll()
                //swagger资源不拦截
                .antMatchers(SWAGGER_RESOURCES).permitAll()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated();

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.accessDeniedHandler(commonAccessDeniedHandler)
                .authenticationEntryPoint(commonAuthenticationEntryPoint);
    }
}
